import gulp from "gulp";
import GulpSSH from "gulp-ssh";
// 也可以是 import fs from "fs"; 区别是同步和异步
import fs from "fs/promises";
import path from "path";
import { fileURLToPath } from "url";
import { serviceConfigObj } from "./appConfig/serviceConfig.mjs";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const shellDataList = [];
let jsonData;
const currentSetting = {
  // eslint-disable-next-line no-undef
  filePath: path.join(__dirname, "./appConfig/gulp/", `${process.env.NODE_ENV}.json`),
  // eslint-disable-next-line no-undef
  NODE_ENV: process.env.NODE_ENV,
  ...serviceConfigObj
};
// eslint-disable-next-line no-undef
const gulpSSH = new GulpSSH({
  ignoreErrors: false,
  sshConfig: {
    host: currentSetting.HOST,
    port: currentSetting.PORT,
    username: currentSetting.USERNAME,
    password: currentSetting.PASSWORD
  }
});
async function initiazationFn() {
  let json = await fs.readFile(currentSetting.filePath, { encoding: "utf-8" });
  jsonData = !json ? { nextVersion: 1, currentVersion: 0, serviceVersion: [] } : JSON.parse(json);
  jsonData.serviceVersion.push({ version: jsonData.nextVersion, timestamp: new Date().getTime() });
  jsonData.nextVersion += 1;
  jsonData.currentVersion += 1;
  // filter 加async会过滤失败
  jsonData.serviceVersion = jsonData.serviceVersion.filter((item) => {
    const itemTime = new Date(item.timestamp);
    const hourDifference = Math.abs(new Date() - itemTime) / 3600 / 1000;
    const versionDifference = jsonData.serviceVersion[jsonData.serviceVersion.length - 1].version - item.version;
    let isRemain = hourDifference <= 1 || versionDifference <= 3;
    if (!isRemain) {
      // 在task里面 对task数组进行push push进去的task是不会执行的 因为该task在刚刚开始执行的时候就通过扩展运算符决定了有哪些task
      shellDataList.push(function ab() {
        return gulpSSH.shell(`rm -rf ${serviceConfigObj.SERVICE_URL}/assets/**.${item.version}.*`);
      });
    }
    return isRemain;
  });
}
await initiazationFn();
function uploadFileFn() {
  return gulp.src(`./dist/**`).pipe(gulpSSH.dest(currentSetting.SERVICE_URL));
}
async function updateSettingFn() {
  await fs.writeFile(currentSetting.filePath, JSON.stringify(jsonData));
}
// 当从任务（task）中返回 stream、promise、event emitter、child process 或 observable 时，成功或错误值将通知 gulp 是否继续执行或结束。如果任务（task）出错，gulp 将立即结束执行并显示该错误。
gulp.task("deploy", gulp.series(uploadFileFn, ...shellDataList, updateSettingFn));
gulp.task("list-remote-files", function () {
  return gulpSSH.exec(["ls -l /"], { filePath: "files.txt" }).pipe(gulp.dest("logs"));
});
